// pages/pay/getpayvalue/getpayvalue.js
const app = new getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    out_trade_no: '',
    pay_money: 0.00,
    nick_name:'',
    out_trade_no: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let out_trade_no = options.out_trade_no;

    app.sendRequest({
      url: 'api.php?s=pay/getPayValue',
      data: {
        out_trade_no: out_trade_no,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let code = res.code;
        let data = res.data;
        let pay_money = data.pay_value.pay_money;
        let nick_name = data.nick_name;
        if (code == 0) {
          that.setData({
            out_trade_no: out_trade_no,
            pay_money: pay_money,
            nick_name: nick_name
          })
        }
        console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 确认支付
   */
  payOrder: function(event) {
    let that = this;
    let out_trade_no = that.data.out_trade_no;
    let openid = app.globalData.openid;

    app.sendRequest({
      url: 'api.php?s=pay/appletWechatPay',
      data: {
        out_trade_no: out_trade_no,
        openid: openid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let data = res.data;
        let out_trade_no = that.data.out_trade_no;
        //let timeStamp = Date.parse(new Date()) / 1000;
        console.log(res)
        wx.requestPayment({
          timeStamp: data.timestamp.toString(),
          nonceStr: data.nonce_str,
          'package': 'prepay_id=' + data.prepay_id,
          signType: 'MD5',
          paySign: data.PaySign,
          success: function(){
            wx.reLaunch({
              url: '/pages/pay/paycallback/paycallback?status=1&out_trade_no=' + out_trade_no,
            })
          },
          fail: function(res){
            console.log(res);
            if (res.errMsg == 'requestPayment:fail cancel') {
              wx.reLaunch({
                url: '/pages/pay/paycallback/paycallback?status=-1&out_trade_no=' + out_trade_no,
              })
              app.showBox(that, '取消支付');
            }
          },
          complete: function(res){
            // wx.reLaunch({
            //   url: '/pages/pay/paycallback/paycallback',
            // })
          }
        })
      }
    })
  }
})